package com.iweb.report_statistic.servlet;

import com.alibaba.fastjson.JSONObject;
import com.iweb.report_statistic.model.Report;
import com.iweb.report_statistic.model.Total;
import com.iweb.report_statistic.service.ReportService;
import com.iweb.report_statistic.service.ReportServiceImpl;
import com.iweb.report_statistic.service.TotalService;
import com.iweb.report_statistic.service.TotalServiceImpl;
import com.iweb.util.PageModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(value = "*.report")
public class ReportServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath =req.getServletPath();
        switch (servletPath){
            case "/toReport.report":
                toReport(req,resp);
                break;
            case "/selectByPage.report":
                selectByPage(req,resp);
                break;
            case "/total.report":
                selectByTotal(req,resp);
                break;
            default:
                break;
        }
    }


    //重定向到报表模块
    protected void toReport(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/report.html").forward(req,resp);
    }


    //分页查询


    ReportService reportService = new ReportServiceImpl();
    TotalService totalService =new TotalServiceImpl();
    protected void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        HttpSession session = req.getSession();
//        if(session.getAttribute("manager")==null){
//            resp.getWriter().print("");
//            return;
//        }
        String pageNo =req.getParameter("pageNo") == null ? "1" : req.getParameter("pageNo");
        String likeValue = req.getParameter("likeValue") == null ? "" : req.getParameter("likeValue");
        PageModel pageModel = new PageModel();
        pageModel.setPageNo(Integer.valueOf(pageNo));
        pageModel.setLikeValue(likeValue);
        List<Report> reports = reportService.selectByPage(pageModel);
        pageModel.setRecordList(reports);
        String jsonObj = JSONObject.toJSONString(pageModel);
        resp.getWriter().print(jsonObj);
    }

    protected void selectByTotal(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Total total = totalService.total();
        String jsonObj = JSONObject.toJSONString(total);
        resp.getWriter().print(jsonObj);
    }
}
